

/**
 * 2、退出登录
 */
$(function () {
    $(".logout").click(function (e) {
        e.preventDefault();
        //1、清空localStorage
        localStorage.clear();
        //2、执行页面跳转到login.html
        location.replace("login.html");
    });
});

/**
 * 旧密码失去焦点时进行验证当前的密码是否正确
 */
$(function () {
    $("#oldPassword").blur(function () {
        checkPass();
    });
    $("#newPassword").blur(function () {
        checkNewPassword($(this));
    });

    $("#reNewPassword").blur(function () {
        checkReNewPassword($(this));
    });

    //提交表单进行密码修改
    $("#submit").click(function (e) {
        e.preventDefault();
        if (checkPass() & checkNewPassword($("#oldPassword")) & checkReNewPassword($("#reNewPassword"))) {
            $.put("http://146.56.230.35:3007/users/updatePassword", {
                    userPassword: $("#newPassword").val(),
                    id: JSON.parse(localStorage.getItem("user")).data.id
                },
                res => {
                    console.log(res);
                    let object = JSON.parse(res);
                    if (object.affectedRows) {
                        localStorage.clear();
                        location.replace("login.html");
                    } else {
                        alert("修改失败！");
                    }
                })
        }
    });

});

function checkPass() {
    let v = $("#oldPassword").val();
    let pass = JSON.parse(localStorage.getItem("user")).data.userPassword;
    console.log(pass);
    $.ajaxSettings.async = false;
    let flag = false;
    $.post("http://146.56.230.35:3007/md5", {v: v}, function (res) {
        console.log(res);
        flag = pass === res;
    });
    if (!flag) {
        $("#oldPassword").parent().removeClass("ok").addClass("error");
        return false;
    }
    $.ajaxSettings.async = true;
    $("#oldPassword").parent().removeClass("error").addClass("ok");
    return true;
}

//新密码的验证
function checkNewPassword(t) {
    let span = t.next();
    let div = t.parent();
    let v = t.val();
    if (!v) {
        div.removeClass("ok").addClass("error");
        span.html("密码非空！");
        return false;
    }
    let reg = /^[a-zA-Z]\w{5,11}$/;
    if (!reg.test(v)) {
        div.removeClass("ok").addClass("error");
        span.html("密码首字开头6-12位！");
        return false;
    }
    div.removeClass("error").addClass("ok");
    span.html("新密码正确！");
    return true;
};


function checkReNewPassword(t) {
    if (checkNewPassword($("#newPassword"))) {
        let v = t.val();
        if (v == $("#newPassword").val()) {
            t.parent().removeClass("error").addClass("ok");
            t.next().html("确认新密码正确！");
            return true;
        }
    }
    t.parent().removeClass("ok").addClass("error");
    t.next().html("确认新密码错误！");
    return false;
}
